/**   
 * @Title: UpdateWidgetService.java
 * @Package com.willter.weather.app
 * @Description: TODO(描述文件)
 * 		<p>
 * @author willter
 * @date 2012-9-16
 */
package com.willter.weather.app;

import java.util.Date;

import android.annotation.SuppressLint;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.IBinder;
import android.util.Log;
import android.widget.RemoteViews;

/**
 * @ClassName: UpdateWidgetService
 * @Description: 更新天气widget组件的后台服务
 *               <p>
 * @author willter
 * @date 2012-9-16
 */
public class UpdateWidgetService extends Service {

	private AlarmManager alarm;
	private PendingIntent pintent;

	/**
	 * (非 Javadoc)
	 * 
	 * @Title: onBind
	 * @Description: TODO(覆盖父类方法)
	 *               <p>
	 * @author willter
	 * @date 2012-9-16
	 *       <p>
	 * @param arg0
	 * @return
	 * @see android.app.Service#onBind(android.content.Intent)
	 */
	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	/**
	 * @Title: onStart
	 * @Description: 开始服务
	 *               <p>
	 * @author willter
	 * @date 2012-9-16
	 *       <p>
	 * @param intent
	 * @param startId
	 * @see android.app.Service#onStart(android.content.Intent, int)
	 */
	@Override
	public void onStart(Intent intent, int startId) {
		super.onStart(intent, startId);

		Log.i("widget Service", "======================update widget===========================");
		// widget的布局对象
		RemoteViews views = WeatherWidget.getWeatherView(this);
		// AppWidgetManager widget管理器
		AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(this);

		int[] appids = appWidgetManager.getAppWidgetIds(new ComponentName(this, WeatherWidget.class));

		// 获取城市码
		SharedPreferences sp = getSharedPreferences(SetCityActivity.CITY_CODE_FILE, SetCityActivity.MODE_PRIVATE);
		String cityCode = sp.getString("code", "");
		if (null != cityCode && cityCode.trim().length() > 0) {
			Log.i("widget", "===================update  weather===========================");
			WeatherWidget.updateAppWidget(views, this, appWidgetManager, cityCode);
		}

		appWidgetManager.updateAppWidget(appids, views);

		// 获取当前时间
		Date date = new Date();
		long now = date.getTime();
		long unit = 1 * 60 * 1000; // 间隔一分钟
		int s = date.getSeconds(); // 得到秒数
		unit = 60000 - s * 1000; // 将时间精确到秒

		pintent = PendingIntent.getService(this, 0, intent, 0);

		// 计时器
		alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
		// 设置间隔指定的时间后启动
		alarm.set(AlarmManager.RTC_WAKEUP, now + unit, pintent);
	}

	@Override
	public void onDestroy() {
		// 取消定时管理
		if (null != alarm) {
			alarm.cancel(pintent);
		}
		super.onDestroy();
	}
}
